<?php

namespace App\Service\playlet;
use App\Model\Applet;
use App\Model\AppletCompany;
use App\Service\CommicService;
use App\Model\Company;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;

class CompanyService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $status      = $params['status'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = Company::query()->select(['id','status','name','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if ($status != '') {
            $query->where(['status' => $status]);
        }
        $models = $query->orderBy('updated_at','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['status_name']  = self::$commonStatus[$item->status];


            $appletCompanyInfo = AppletCompany::query()->where(['company_id' => $item->id])->get();
            $appletName = '';

            foreach ($appletCompanyInfo as $appletCompany){
                if(!empty($appletCompany->applet)){
                    $appletName .= $appletCompany->applet->name.',';
                }

            }
            $data['applet_name'] = substr($appletName,0,-1);
            $selectData[] =$data;

        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }

    public function createOrUpdate(Array $postData,Company $companyInfo = null){
        $name = $postData['name'];
        $status = $postData['status'];
        $applet_ids = $postData['applet_ids'] ?? [];
        Db::beginTransaction();
        try {

            $model = !empty($companyInfo)? $companyInfo : new Company();
            $model->name = $name;
            $model->status = $status;
            if($model->save()){
                if(!empty($applet_ids)){
                    //查找是否有对应的小程序
                    $appletIds = Applet::query()->whereIn('id',$applet_ids)->pluck('id')->toArray();
                    if(!empty($appletIds)){
                        //删除之前绑定得小程序，重新绑定
                        AppletCompany::query()->where(['company_id' => $model->id])->delete();
                        foreach ($appletIds as $applet_id){
                            $insertModel = new AppletCompany();
                            $insertModel->company_id =  $model->id;
                            $insertModel->applet_id =  $applet_id;
                            $insertModel->save();
                        }
                    }
                }
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }else{
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
            }

        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }

    }
}